$(function () {
    $('#remark').summernote({height: 200});
    getSafetyCodeClass("eventTypeQuery", "eventType");
    getSafetyCodeClass("eventType", "eventType");
    query();
    jeDate("#beginTimeQuery", {
        format: "YYYY-MM-DD hh:mm"
    });
    jeDate("#endTimeQuery", {
        format: "YYYY-MM-DD hh:mm"
    });
    jeDate("#occTime", {
        format: "YYYY-MM-DD hh:mm"
    });
    $(".js-simple-query").unbind("click").click(function () {
        $("#myTable").bootstrapTable("refresh");
    })
    $("#entId").select2({
        theme: "bootstrap",
        allowClear: true,
        placeholder: "请输入企业名称或法人姓名",
        query: function (query) {
            var url = "/ret/safetyget/selectEntInfoByName";
            var param = {search: query.term}; // 查询参数，query.term为用户在select2中的输入内容.
            var type = "json";
            var data = {results: []};
            $.post(
                url,
                param,
                function (datas) {
                    var datalist = datas.list;
                    for (var i = 0, len = datalist.length; i < len; i++) {
                        var land = datalist[i];
                        var option = {
                            "id": land.entId,
                            "text": land.entName
                        };
                        data.results
                            .push(option);
                    }
                    query.callback(data);
                }, type);

        },
        escapeMarkup: function (markup) {
            return markup;
        },
        minimumInputLength: 2,
        formatResult: function (data) {
            return '<div class="select2-user-result">' + data.text + '</div>'
        },
        formatSelection: function (data) {
            return data.text;
        },
        initSelection: function (data, cb) {
            cb(data);
        }
    });
})

function query() {
    $("#myTable").bootstrapTable({
        url: '/ret/safetyget/getSafetyEventList',
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: true,//是否显示 数据条数选择框
        sortable: true,//排序
        sortOrder: "desc",
        search: true,//启用搜索
        showColumns: true,//是否显示 内容列下拉框
        showRefresh: true,//显示刷新按钮
        idField: 'eventId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        },
            {
                field: 'num',
                title: sysmsg['SORT_NO'],//标题  可不加
                width: '50px',
                formatter: function (value, row, index) {
                    return index + 1;
                }
            },
            {
                field: 'title',
                title: '事件标题',
                width: '150px',
                formatter: function (value, row, index) {
                    return "<a style=\"cursor: pointer;\" href=\"javascript:void(0);details('" + row.eventId + "');\">" + value + "</a>";
                }
            },
            {
                field: 'entName',
                width: '150px',
                title: '关联企业'
            },
            {
                field: 'eventType',
                title: '事件类型',
                width: '50px',
                formatter: function (value, row, index) {
                    return getSafetyCodeClassName(value, "eventType");
                }
            },
            {
                field: 'reportPersoner',
                width: '100px',
                title: '上报人'
            },
            {
                field: 'occTime',
                width: '100px',
                title: '发生时间'
            },
            {
                field: 'address',
                title: '发生地址',
                width: '100px'
            },
            {
                field: 'opt',
                title: '操作',
                align: 'center',
                width: '100px',
                formatter: function (value, row, index) {
                    return createOptBtn(row.eventId);
                }
            }],
        onClickCell: function (field, value, row, $element) {
            //alert(row.SystemDesc);
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    var temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order,
        eventType: $("#eventTypeQuery").val(),
        beginTime: $("#beginTimeQuery").val(),
        endTime: $("#endTimeQuery").val()
    };
    return temp;
}

function createOptBtn(eventId) {
    let html = "<a href=\"javascript:void(0);edit('" + eventId + "')\" class=\"btn btn-primary btn-xs\" >编辑</a>&nbsp;&nbsp;";
    html += "<a href=\"javascript:void(0);deleteEvent('" + eventId + "')\" class=\"btn btn-darkorange btn-xs\" >删除</a>";
    return html;
}

function edit(eventId) {
    $("#listdiv").hide();
    $("#eventdiv").show();
    $(".js-back-btn").unbind("click").click(function () {
        goback();
    })
    document.getElementById("form1").reset();
    $("#remark").code("")
    $("#attach").attr("data_value", "");
    $("#show_attach").empty();
    $.ajax({
        url: "/ret/safetyget/getSafetyEventById",
        type: "post",
        dataType: "json",
        data: {
            eventId: eventId
        },
        success: function (data) {
            if (data.status == "200") {
                let info = data.list;
                for (let id in info) {
                    if (id == "attach") {
                        $("#attach").attr("data_value", info.attach);
                        createAttach("attach", 4);
                    } else if (id == "remark") {
                        $("#remark").code(info[id]);
                    } else if (id == "entId") {
                        $.ajax({
                            url: "/ret/safetyget/getSafetyEntInfoById",
                            type: "post",
                            dataType: "json",
                            data: {
                                entId: info[id]
                            },
                            success: function (res) {
                                let entInfo = res.list;
                                if (entInfo) {
                                    $('#entId').select2({
                                        data: [{
                                            "id": entInfo.entId,
                                            "text": entInfo.entName
                                        }]
                                    }).val(info[id]).trigger('change');
                                }
                            }
                        });

                    } else {
                        $("#" + id).val(info[id]);
                    }
                }
                $(".js-update-save").unbind("click").click(function () {
                    updateEvent(evnetId);
                })
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })

}

function goback() {
    $("#eventdiv").hide();
    $("#listdiv").show();
}


function updateEvent(eventId) {
    if($("#title").val()=="")
    {
        layer.msg("事件标题不能为空！");
        return;
    }
    $.ajax({
        url: "/set/safetyset/updateSafetyEvent",
        type: "post",
        dataType: "json",
        data: {
            eventId: eventId,
            sortNo: $("#sortNo").val(),
            eventType: $("#eventType").val(),
            title: $("#title").val(),
            entId: $("#entId").val(),
            reportPersoner: $("#reportPersoner").val(),
            occTime: $("#occTime").val(),
            address: $("#address").val(),
            remark: $("#remark").code(),
            attach: $("#attach").attr("data_value")
        },
        success: function (data) {
            if (data.status == "200") {
                layer.msg(sysmsg[data.msg]);
                $('#myTable').bootstrapTable('refresh');
                goback();
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else if (data.status == "500") {
                console.log(data.msg);
            }
        }
    })
}

function deleteEvent(eventId) {
    if (confirm(sysmsg['OPT_CONFIRM_DELETE'])) {
        $.ajax({
            url: "/set/safetyset/deleteSafetyEvent",
            type: "post",
            dataType: "json",
            data: {eventId: eventId},
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $('#myTable').bootstrapTable('refresh');
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else if (data.status == "500") {
                    console.log(data.msg);
                }
            }
        })
    }
}

function details(eventId) {
    window.open("/app/core/safety/enteventdetails?eventId=" + eventId);
}
